import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../../shared/utils/responsive_utils.dart';

class MistakesPage extends StatefulWidget {
  const MistakesPage({super.key});

  @override
  State<MistakesPage> createState() => _MistakesPageState();
}

class _MistakesPageState extends State<MistakesPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  String _selectedFilter = '全部';
  final List<String> _filters = ['全部', '数学', '英语', '语文'];
  final List<Map<String, dynamic>> _mistakes = [
    {
      'id': '1',
      'subject': '数学',
      'title': '解方程：2x + 3 = 7',
      'errorType': '计算错误',
      'reviewStatus': '待复习',
      'nextReview': '今天',
      'mastery': 0.3,
    },
    {
      'id': '2',
      'subject': '英语',
      'title': '选择正确的时态：I ___ to school every day.',
      'errorType': '语法错误',
      'reviewStatus': '已掌握',
      'nextReview': '3天后',
      'mastery': 0.8,
    },
    {
      'id': '3',
      'subject': '语文',
      'title': '古诗文默写：《静夜思》',
      'errorType': '记忆错误',
      'reviewStatus': '待复习',
      'nextReview': '明天',
      'mastery': 0.5,
    },
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            if (context.canPop()) {
              context.pop();
            } else {
              context.go('/dashboard');
            }
          },
        ),
        title: const Text('错题本'),
        actions: <Widget>[
          IconButton(onPressed: () {}, icon: const Icon(Icons.search)),
          IconButton(onPressed: () {}, icon: const Icon(Icons.more_vert)),
        ],
      ),
      body: Column(
        children: <Widget>[
          _buildFilterBar(),
          _buildTabBar(),
          Expanded(child: _buildTabBarView()),
        ],
      ),
    );
  }

  Widget _buildFilterBar() {
    return Container(
      padding: EdgeInsets.all(
        ResponsiveUtils.getResponsiveSpacing(context, 16),
      ),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children:
              _filters.map((filter) {
                final isSelected = _selectedFilter == filter;
                return GestureDetector(
                  onTap: () {
                    setState(() {
                      _selectedFilter = filter;
                    });
                  },
                  child: Container(
                    margin: EdgeInsets.only(
                      right: ResponsiveUtils.getResponsiveSpacing(context, 12),
                    ),
                    padding: EdgeInsets.symmetric(
                      horizontal: ResponsiveUtils.getResponsiveSpacing(
                        context,
                        16,
                      ),
                      vertical: ResponsiveUtils.getResponsiveSpacing(
                        context,
                        8,
                      ),
                    ),
                    decoration: BoxDecoration(
                      color:
                          isSelected
                              ? Theme.of(context).colorScheme.primaryContainer
                              : Theme.of(
                                context,
                              ).colorScheme.surfaceContainerHighest,
                      borderRadius: BorderRadius.circular(
                        ResponsiveUtils.getResponsiveRadius(context, 20),
                      ),
                      border:
                          isSelected
                              ? Border.all(
                                color: Theme.of(context).colorScheme.primary,
                              )
                              : null,
                    ),
                    child: Text(
                      filter,
                      style: TextStyle(
                        color:
                            isSelected
                                ? Theme.of(context).colorScheme.primary
                                : Theme.of(context).colorScheme.onSurface,
                        fontWeight:
                            isSelected ? FontWeight.w600 : FontWeight.w500,
                      ),
                    ),
                  ),
                );
              }).toList(),
        ),
      ),
    );
  }

  Widget _buildTabBar() {
    return Container(
      margin: EdgeInsets.symmetric(
        horizontal: ResponsiveUtils.getResponsiveSpacing(context, 16),
      ),
      decoration: BoxDecoration(
        color: Theme.of(
          context,
        ).colorScheme.surfaceContainerHighest.withOpacity(0.7),
        borderRadius: BorderRadius.circular(
          ResponsiveUtils.getResponsiveRadius(context, 24),
        ),
        border: Border.all(
          color: Theme.of(context).colorScheme.outline.withOpacity(0.08),
        ),
      ),
      child: TabBar(
        controller: _tabController,
        labelColor: Theme.of(context).colorScheme.primary,
        unselectedLabelColor: Theme.of(
          context,
        ).colorScheme.onSurface.withOpacity(0.6),
        labelStyle: const TextStyle(fontWeight: FontWeight.w700),
        unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600),
        indicatorSize: TabBarIndicatorSize.tab,
        indicatorPadding: EdgeInsets.all(
          ResponsiveUtils.getResponsiveSpacing(context, 4),
        ),
        overlayColor: MaterialStateProperty.resolveWith(
          (states) => Colors.transparent,
        ),
        indicator: BoxDecoration(
          gradient: LinearGradient(
            colors: <Color>[
              Theme.of(context).colorScheme.primary.withOpacity(0.20),
              Theme.of(context).colorScheme.primary.withOpacity(0.35),
            ],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          borderRadius: BorderRadius.circular(
            ResponsiveUtils.getResponsiveRadius(context, 20),
          ),
          border: Border.all(
            color: Theme.of(context).colorScheme.primary.withOpacity(0.35),
            width: 1,
          ),
          boxShadow: <BoxShadow>[
            BoxShadow(
              color: Theme.of(context).colorScheme.primary.withOpacity(0.18),
              blurRadius: ResponsiveUtils.getResponsiveSpacing(context, 8),
              offset: Offset(
                0,
                ResponsiveUtils.getResponsiveSpacing(context, 3),
              ),
            ),
          ],
        ),
        tabs: const <Widget>[
          Tab(text: '待复习'),
          Tab(text: '已掌握'),
          Tab(text: '全部'),
        ],
      ),
    );
  }

  Widget _buildTabBarView() {
    return TabBarView(
      controller: _tabController,
      children: <Widget>[
        _buildMistakeList('待复习'),
        _buildMistakeList('已掌握'),
        _buildMistakeList('全部'),
      ],
    );
  }

  Widget _buildMistakeList(String status) {
    final filteredMistakes =
        _mistakes.where((mistake) {
          if (status == '全部') return true;
          return mistake['reviewStatus'] == status;
        }).toList();

    if (filteredMistakes.isEmpty) {
      return _buildEmptyState(status);
    }

    return ListView.builder(
      padding: EdgeInsets.all(
        ResponsiveUtils.getResponsiveSpacing(context, 16),
      ),
      itemCount: filteredMistakes.length,
      itemBuilder: (context, index) {
        final mistake = filteredMistakes[index];
        return _buildMistakeCard(mistake);
      },
    );
  }

  Widget _buildEmptyState(String status) {
    final cs = Theme.of(context).colorScheme;
    return Center(
      child: Padding(
        padding: EdgeInsets.all(
          ResponsiveUtils.getResponsiveSpacing(context, 24),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(
              Icons.check_circle_outline,
              size: ResponsiveUtils.getResponsiveIconSize(context, 72),
              color: cs.onSurface.withOpacity(0.3),
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
            Text(
              status == '已掌握' ? '太棒了！没有错题' : '暂无错题',
              style: TextStyle(
                fontSize: ResponsiveUtils.getResponsiveFontSize(context, 18),
                fontWeight: FontWeight.w700,
                color: cs.onSurface.withOpacity(0.75),
              ),
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 8)),
            Text(
              status == '已掌握' ? '继续保持，你已经掌握得很好' : '拍题后会自动加入错题本',
              style: TextStyle(color: cs.onSurface.withOpacity(0.55)),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 20)),
            if (status != '已掌握')
              FilledButton.icon(
                onPressed: () => context.go('/capture'),
                icon: const Icon(Icons.photo_camera),
                label: const Text('去拍题'),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildMistakeCard(Map<String, dynamic> mistake) {
    final ColorScheme cs = Theme.of(context).colorScheme;
    final bool isMastered = mistake['reviewStatus'] == '已掌握';

    return Dismissible(
      key: Key(mistake['id']),
      direction: DismissDirection.endToStart,
      background: Container(
        alignment: Alignment.centerRight,
        padding: EdgeInsets.only(
          right: ResponsiveUtils.getResponsiveSpacing(context, 20),
        ),
        color: Colors.green,
        child: Icon(Icons.check, color: Colors.white),
      ),
      onDismissed: (direction) {
        // TODO: 标记为已掌握
        setState(() {
          // 更新状态
        });
      },
      child: Padding(
        padding: EdgeInsets.only(
          bottom: ResponsiveUtils.getResponsiveSpacing(context, 12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            // 动效包裹
            AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              curve: Curves.easeOut,
              padding: EdgeInsets.all(
                ResponsiveUtils.getResponsiveSpacing(context, 16),
              ),
              decoration: BoxDecoration(
                color: cs.surfaceContainerHighest,
                borderRadius: BorderRadius.circular(
                  ResponsiveUtils.getResponsiveRadius(context, 12),
                ),
                border:
                    isMastered
                        ? Border.all(color: Colors.green.withOpacity(0.3))
                        : null,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.03),
                    blurRadius: ResponsiveUtils.getResponsiveSpacing(
                      context,
                      8,
                    ),
                    offset: Offset(
                      0,
                      ResponsiveUtils.getResponsiveSpacing(context, 4),
                    ),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: _getSubjectColor(
                            mistake['subject'],
                          ).withOpacity(0.1),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          mistake['subject'],
                          style: TextStyle(
                            color: _getSubjectColor(mistake['subject']),
                            fontSize: ResponsiveUtils.getResponsiveFontSize(
                              context,
                              12,
                            ),
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                      const Spacer(),
                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: ResponsiveUtils.getResponsiveSpacing(
                            context,
                            8,
                          ),
                          vertical: ResponsiveUtils.getResponsiveSpacing(
                            context,
                            4,
                          ),
                        ),
                        decoration: BoxDecoration(
                          color:
                              isMastered
                                  ? Colors.green.withOpacity(0.1)
                                  : Colors.orange.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(
                            ResponsiveUtils.getResponsiveRadius(context, 12),
                          ),
                        ),
                        child: Text(
                          mistake['reviewStatus'],
                          style: TextStyle(
                            color: isMastered ? Colors.green : Colors.orange,
                            fontSize: ResponsiveUtils.getResponsiveFontSize(
                              context,
                              12,
                            ),
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: ResponsiveUtils.getResponsiveSpacing(context, 12),
                  ),
                  Text(
                    mistake['title'],
                    style: TextStyle(
                      fontSize: ResponsiveUtils.getResponsiveFontSize(
                        context,
                        16,
                      ),
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  SizedBox(
                    height: ResponsiveUtils.getResponsiveSpacing(context, 8),
                  ),
                  Row(
                    children: <Widget>[
                      Icon(
                        Icons.error_outline,
                        size: ResponsiveUtils.getResponsiveIconSize(
                          context,
                          16,
                        ),
                        color: cs.onSurface.withOpacity(0.6),
                      ),
                      SizedBox(
                        width: ResponsiveUtils.getResponsiveSpacing(context, 4),
                      ),
                      Text(
                        mistake['errorType'],
                        style: TextStyle(
                          fontSize: ResponsiveUtils.getResponsiveFontSize(
                            context,
                            12,
                          ),
                          color: cs.onSurface.withOpacity(0.6),
                        ),
                      ),
                      const Spacer(),
                      Text(
                        '下次复习：${mistake['nextReview']}',
                        style: TextStyle(
                          fontSize: ResponsiveUtils.getResponsiveFontSize(
                            context,
                            12,
                          ),
                          color: cs.onSurface.withOpacity(0.6),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: ResponsiveUtils.getResponsiveSpacing(context, 12),
                  ),
                  LinearProgressIndicator(
                    value: mistake['mastery'],
                    backgroundColor: cs.onSurface.withOpacity(0.1),
                    valueColor: AlwaysStoppedAnimation<Color>(
                      isMastered ? Colors.green : cs.primary,
                    ),
                  ),
                  SizedBox(
                    height: ResponsiveUtils.getResponsiveSpacing(context, 8),
                  ),
                  Row(
                    children: <Widget>[
                      Text(
                        '掌握度：${(mistake['mastery'] * 100).toInt()}%',
                        style: TextStyle(
                          fontSize: ResponsiveUtils.getResponsiveFontSize(
                            context,
                            12,
                          ),
                          color: cs.onSurface.withOpacity(0.6),
                        ),
                      ),
                      const Spacer(),
                      TextButton(onPressed: () {}, child: const Text('查看详情')),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Color _getSubjectColor(String subject) {
    switch (subject) {
      case '数学':
        return Colors.blue;
      case '英语':
        return Colors.green;
      case '语文':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }
}
